import { Form, Input, message, Modal, TreeSelect } from 'antd';
import { useCallback, useEffect, useState } from 'react';

import { RegionForm } from '@/api/services/security/menuService';
import regionService from '@/api/services/security/regionService';
import { hasPermission } from '@/utils/permission';
import { listToTree } from '@/utils/tree';

import { Region } from './type';

import { ModalProps } from '#/entity';

// eslint-disable-next-line func-names
export default function ({ title, show, formValue, onOk, onCancel }: ModalProps<Region>) {
  const [inputPrefix, setInputPrefix] = useState('');
  const [form] = Form.useForm();
  const [regionsList, setRegionsList] = useState<Region[]>([]);
  const loadRegionData = useCallback(async () => {
    setLoading(true);
    regionService.tree().then((res) => {
      setRegionsList(res);
      setRegions(listToTree(res));
    });
    setLoading(false);
  }, []);
  const onFinish = useCallback(
    async (values: any) => {
      let submitData: any = {};

      if (title === '修改区域') {
        submitData = {
          ...values,
          parentId: values.parentId.id || formValue.parent?.id || 0,
          code: inputPrefix + values.code,
        };
        regionService.updateRegion(formValue.id!, submitData).then(() => {
          message.success('修改成功');
          onOk(values);
        });
      } else if (title === '创建区域') {
        submitData = {
          ...values,
          parentId: values.parentId.id || formValue.id || 0,
          code: inputPrefix + values.code,
        };
        regionService.createRegion(submitData).then(() => {
          message.success('创建成功');
          onOk(values);
        });
      }
      await loadRegionData();
    },
    [formValue, loadRegionData, onOk, title, inputPrefix],
  );

  const [regions, setRegions] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    loadRegionData();
  }, [loadRegionData]); // 组件挂载时加载数据

  const modalRender = useCallback(
    (dom: React.ReactNode) => (
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        onFinish={onFinish}
        clearOnDestroy
        layout="horizontal"
      >
        {dom}
      </Form>
    ),
    [form, formValue, onFinish],
  );
  const defaultValue = () => {
    console.log('defaultValueformValue', formValue);
    if (title === '创建区域') {
      return formValue.id;
    }
    return formValue?.parent?.id;
  };

  const getName = () => {
    if (title === '创建区域') {
      return '';
    }
    return formValue?.name;
  };
  useEffect(() => {
    form.setFieldsValue({
      name: getName(),
    });
  });
  const prefix = useCallback(
    // 设置前缀inputPrefix
    () => {
      if (title === '修改区域') {
        setInputPrefix(formValue.parent?.code || '');
      }
      if (title === '创建区域') {
        setInputPrefix(formValue.code);
        formValue.code = ''; // 将输入框清空，但是关闭窗口要重新设置为
      }
      return '';
    },
    [title, formValue],
  );
  useEffect(() => {
    prefix();
    // setInputPrefix(formValue.code);
  }, [formValue, prefix]);
  const onSelectTreeSelect = useCallback(
    (value: any) => {
      const selectItem = regionsList.filter((item) => {
        return value === item.id;
      });
      setInputPrefix(selectItem[0].code);
    },

    [regionsList, inputPrefix],
  );
  return (
    <Modal
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{
        autoFocus: true,
        htmlType: 'submit',
        disabled: !hasPermission('SECURITY:MENU:UPDATE') && !!formValue.id,
      }}
      destroyOnClose
      modalRender={modalRender}
    >
      <Form.Item<RegionForm> label="名称" name="name" rules={[{ required: true }]}>
        <Input autoFocus />
      </Form.Item>

      <Form.Item name={['parentId', 'id']} label="上级区域">
        <TreeSelect
          fieldNames={{
            label: 'name',
            value: 'id',
            children: 'children',
          }}
          onSelect={onSelectTreeSelect}
          allowClear
          treeData={regions}
          defaultValue={defaultValue}
          placeholder="请选择上级区域"
          style={{ width: '100%', maxHeight: 900 }}
          loading={loading}
          popupMatchSelectWidth={false}
        />
        {/* <Cascader
          options={regions}
          expandTrigger="hover"
          displayRender={(labels: string[]) => {
            return labels[labels.length - 1];
          }}
          onChange={(value) => {
            console.log(value);
          }}
        /> */}
      </Form.Item>

      <Form.Item<RegionForm>
        label="区域编号"
        name="code"
        rules={[
          {
            required: true,
            message: '请输入编码',
          },
        ]}
      >
        <Input prefix={inputPrefix} maxLength={3} />
        {/* prefix={inputPrefix()} maxLength={maxLength()} */}
      </Form.Item>
    </Modal>
  );
}
